import { dictList } from './base/dict';
import { paramList } from './base/param';
import { getCurrentUser } from '../auth-center';

const dataSource = {
  dict: dictList,
  param: paramList,
};

// ---------------- 模拟静态文件存储缓存数据 ----------------
const cacheStore = {
  dict: {
    hash: 0,
    data: [],
  },
  param: {
    hash: 0,
    data: [],
  },
};
// ---------------- 模拟静态文件存储缓存数据 ----------------

(() => {
  Object.keys(cacheStore).forEach(async (key) => {
    const service = dataSource[key];
    const res = await service.list({ enable: '1' });
    cacheStore[key] = { hash: Date.now(), data: res.list };
  });
})();

export default {
  // 获取缓存数据静态文件的 hash
  'GET /mock/cache/hash': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const hashs = Object.keys(cacheStore).reduce((store, key) => ((store[key] = cacheStore[key].hash), store), {});
    res.json({ code: '0', data: hashs, message: '成功' });
  },
  // 重新生成缓存数据静态文件
  'POST /mock/cache/refresh': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    try {
      const { type } = req.body;
      if (!type) {
        res.json({ code: '-1', message: '缺少参数：type' });
        return;
      }
      const service = dataSource[type];
      const result = await service.list({ enable: '1' });

      cacheStore[type] = { hash: Date.now(), data: result.list };

      res.json({ code: '0', message: '成功' });
    } catch (error) {
      res.json({ code: '-1', message: '失败' });
    }
  },
  // ---------------- 模拟静态文件请求 ----------------
  'GET /mock/cache/dict.json': async (_, res) => {
    res.json(cacheStore.dict.data);
  },
  // ---------------- 模拟静态文件请求 ----------------
  'GET /mock/cache/param.json': async (_, res) => {
    res.json(cacheStore.param.data);
  },
};
